package com.sjc.grpc.client.grpc;

import com.sjc.demo.java.grpc.rpc.HelloRequest;
import com.sjc.demo.java.grpc.rpc.HelloResponse;
import com.sjc.demo.java.grpc.rpc.HelloServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class GrpcClient {
    private static Logger log = LoggerFactory.getLogger(GrpcClient.class);

    @Value("${grpc.serverHost}")
    private String host;
    @Value("${grpc.serverPort}")
    private int port;

    /**
     * Grpc客户端channel
     */
    private ManagedChannel channel;
    /**
     * RPC服务端点（stub）
     */
    private HelloServiceGrpc.HelloServiceBlockingStub blockingStub;

    @PostConstruct
    public void init(){
        channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();
        blockingStub = HelloServiceGrpc.newBlockingStub(channel);
    }

    @PreDestroy
    public void destroy(){
        channel.shutdown();
    }

    public String getHello(String userName){
        try{
            HelloRequest request = HelloRequest.newBuilder().setUserName(userName).build();
            // 通过RPC服务端点（stub）发起RPC方法调用
            HelloResponse response = blockingStub.sayHello(request);
            return response.getMessage();
        }catch (Exception e){
            log.error("getHello {}",userName,e);
        }
        return "";
    }
}
